package com.dragon.connector.imServer.handler;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.dragon.common.util.JwtUtil;
import com.dragon.connector.imServer.cocurrent.CallbackTask;
import com.dragon.connector.imServer.cocurrent.CallbackTaskScheduler;
import com.dragon.connector.imServer.serverProcesser.LoginProcesser;
import com.dragon.connector.imServer.session.LocalSession;
import com.dragon.connector.imServer.session.dao.UserCacheDAO;
import com.dragon.connector.imServer.session.entity.SessionCache;
import com.dragon.connector.imServer.session.entity.UserCache;
import com.dragon.connector.imServer.session.service.SessionManger;
import com.dragon.protoJo.bean.msg.ProtoMsg;
import com.dragon.protoJo.bean.msg.UserDTO;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
@Slf4j
public class LoginRequestHandler extends ChannelInboundHandlerAdapter {



    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg == null || !(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
        }

        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        //取得请求类型
        LoginProcesser loginProcesser = SpringUtil.getBean(LoginProcesser.class);
        ProtoMsg.HeadType headType = message.getType();
        if (!headType.equals(loginProcesser.op())) {
            super.channelRead(ctx, msg);
            return;
        }

        // 检测token
        String token = JwtUtil.validateToken(message.getLoginRequest().getToken());

        if(StrUtil.isBlank(token)){
            super.channelRead(ctx,msg);
            return;
        }
        Map<String,String> map = JSON.parseObject(token,Map.class);
        String uid = MapUtil.get(map,"id",String.class);
        //List<String> groupId = MapUtil.get(map,"groupIds",List.class);
        /*获取当前用户是否登录*/
        //获取缓存数据
        UserCacheDAO userCacheDAO = SpringUtil.getBean(UserCacheDAO.class);
        SessionManger sessionManger = SpringUtil.getBean(SessionManger.class);
        UserCache userCache = userCacheDAO.get(uid);
        //根据平台不同，生成不同id，crm平台
        if(userCache != null){
            // 判断是那个平台登录的，如果是设备登录，则直接替换之前的sessionId,并关闭之前socket连接
            Map<String, SessionCache> sessionCacheMap = userCache.getMap();
            for(String key:sessionCacheMap.keySet()){
                SessionCache sessionCache = sessionCacheMap.get(key);
                if(sessionCache.getPlatform().equals(UserDTO.PLATTYPE.WEB)){
                    // 删除当前sessionId的信息
                    sessionManger.removeSession(key,uid);
                }
            }
        }
        // 注册到当前服务器中
        LocalSession session = new LocalSession(ctx);

        // 异步任务返回,并且取消登录的拦截
        CallbackTaskScheduler.add(new CallbackTask<Boolean>() {
            @Override
            public Boolean execute() throws Exception {
                return loginProcesser.action(session,message);
            }

            //异步任务返回
            @Override
            public void onBack(Boolean r) {
                if (r) {
//                    ctx.pipeline().remove(LoginRequestHandler.this);
                    log.info("登录成功:" + session.getUser());
                    // 中转消息
//                        ctx.pipeline().addAfter("login", "chat",   chatRedirectHandler);
                    ctx.pipeline().addAfter("login", "heartBeat", new HeartBeatServerHandler());
                    ctx.pipeline().remove("login");
                } else {
                    SessionManger.inst().closeSession(ctx);

                    log.info("登录失败:" + session.getUser());

                }
            }
            //异步任务异常

            @Override
            public void onException(Throwable t) {
                t.printStackTrace();
                log.info("登录失败:" + session.getUser());
                SessionManger.inst().closeSession(ctx);
            }
        });
    }
}
